package com.github.pig.admin.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pig.admin.model.dto.UserDTO;
import com.github.pig.admin.model.dto.UserInfo;
import com.github.pig.admin.model.entity.SysCommunityUser;
import com.github.pig.admin.model.entity.SysRole;
import com.github.pig.admin.model.entity.SysUser;
import com.github.pig.admin.model.entity.SysUserRole;
import com.github.pig.admin.model.zhgl.community.SelectBean;
import com.github.pig.admin.service.sys.SysRoleService;
import com.github.pig.admin.service.sys.SysUserRoleService;
import com.github.pig.admin.service.sys.SysUserService;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.util.R;
import com.github.pig.common.util.ResponseUtil;
import com.github.pig.common.vo.UserVO;
import com.github.pig.common.web.BaseController;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author lengleng
 * @date 2017/10/28
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUserRoleService sysUserRoleService;



    /**
     * 获取当前用户信息（角色、权限）
     * 并且异步初始化用户部门信息
     *
     * @param userVo 当前用户信息
     * @return 用户名
     */
    @GetMapping("/info")
    public R<UserInfo> user(UserVO userVo) {
        UserInfo userInfo = userService.findUserInfo(userVo);
        return new R<>(userInfo);
    }


    /**
     * 通过ID查询当前用户信息
     *
     * @param id ID
     * @return 用户信息
     */
    @GetMapping("/{id}")
    public UserVO user(@PathVariable Integer id) {
        return userService.selectUserVoById(id);
    }

    /**
     * 通过role_code查询角色信息
     *
     * @return 角色信息
     */
    @GetMapping("/app/{roleCode}")
    public SysRole roleCode(@PathVariable String roleCode) {
        return sysRoleService.selectByCode(roleCode);
    }

    /**
     * 删除用户信息
     *
     * @param id ID
     * @return R
     */
    @ApiOperation(value = "删除用户", notes = "根据ID删除用户")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "int", paramType = "path")
    @DeleteMapping("/{id}")
    public R<Boolean> userDel(@PathVariable Integer id) {
        SysUser sysUser = userService.selectById(id);
        return new R<>(userService.deleteUserById(sysUser));
    }

    /**
     * app添加角色
     *
     * @return success、false
     */
    @PostMapping("/addAppRole")
    public R<Boolean> approle(@RequestBody SysUserRole sysUserRole) {
        return new R<>(sysUserRoleService.insert(sysUserRole));
    }

    /**
     * 添加用户
     *
     * @param userDto 用户信息
     * @return success/false
     */
    @PostMapping
    public R<Boolean> user(@RequestBody UserDTO userDto) {
        R<Boolean> r = new R<>();
        //判断用户名是否重复
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("username",userDto.getUsername());
        List<SysUser> sysUserList = userService.selectList(entityWrapper);
        if(sysUserList!=null&&sysUserList.size()>0){
            r.setMsg("用户名已存在!");
            r.setData(false);
            return r;
        }
        EntityWrapper entityWrapperPh = new EntityWrapper();
        entityWrapperPh.eq("phone",userDto.getPhone());
        List<SysUser> sysUserListPh = userService.selectList(entityWrapperPh);
        if(sysUserListPh!=null&&sysUserListPh.size()>0){
            r.setMsg("手机号已存在!");
            r.setData(false);
            return r;
        }
        if(StringUtils.isBlank(userDto.getPassword())){
            userDto.setPassword(CommonConstant.DEFAULT_PASSWORD);
        }
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userDto, sysUser);
        sysUser.setDelFlag(CommonConstant.STATUS_NORMAL);
        sysUser.setPassword(ENCODER.encode(userDto.getPassword()));
        userService.insert(sysUser);

        userDto.getRole().forEach(roleId -> {
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(sysUser.getUserId());
            userRole.setType(CommonConstant.USER_ROLE_TYPE_YH);
            userRole.setRoleId(roleId);
            userRole.insert();
        });
        userDto.getCommunity().forEach(communityId -> {
            SysCommunityUser sysCommunityUser = new SysCommunityUser();
            sysCommunityUser.setUserId(sysUser.getUserId()+"");
            sysCommunityUser.setCommunityId(communityId);
            sysCommunityUser.insert();
        });
        return new R<>(Boolean.TRUE);
    }

    /**
     * app端新增用户
     * @param userDto
     * @return
     */
    @PostMapping("/addAppUser")
    public R<Boolean> addAppUser(@RequestBody UserDTO userDto) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userDto, sysUser);
        userService.insert(sysUser);
        return new R<>(Boolean.TRUE);
    }

    /**
     * 更新用户信息
     *
     * @param userDto 用户信息
     * @return R
     */
    @PutMapping
    public R<Boolean> userUpdate(@RequestBody UserDTO userDto) {
        SysUser user = userService.selectById(userDto.getUserId());
        if(StringUtils.isNotBlank(userDto.getPassword())){
            userDto.setPassword(ENCODER.encode(userDto.getPassword()));
        }
        return new R<>(userService.updateUser(userDto, user.getUsername()));
    }

    /**
     * 通过用户名查询用户及其角色信息
     *
     * @param username 用户名
     * @return UseVo 对象
     */
    @GetMapping("/findUserByUsername/{username}")
    public UserVO findUserByUsername(@PathVariable String username) {
        return userService.findUserByUsername(username);
    }

    /**
     * 通过手机号查询用户及其角色信息
     *
     * @param mobile 手机号
     * @return UseVo 对象
     */
    @GetMapping("/findUserByMobile/{mobile}")
    public UserVO findUserByMobile(@PathVariable String mobile) {
        return userService.findUserByMobile(mobile);
    }

    /**
     * 通过OpenId查询
     *
     * @param openId openid
     * @return 对象
     */
    @GetMapping("/findUserByOpenId/{openId}")
    public UserVO findUserByOpenId(@PathVariable String openId) {
        return userService.findUserByOpenId(openId);
    }

    /**
     * 分页查询用户
     *
     * @param params 参数集
     * @return 用户集合
     */
    @RequestMapping("/userPage")
    public Page userPage(@RequestParam Map<String, Object> params,String username) {
        Page page = new Page(Integer.parseInt(params.getOrDefault("page", 1).toString())
                , Integer.parseInt(params.getOrDefault("limit", 10).toString()));
        return userService.selectWithRolePage(page,username);
    }

    /**
     * 修改个人信息
     *
     * @param userDto userDto
     * @param userVo  登录用户信息
     * @return success/false
     */
    @PutMapping("/editInfo")
    public R<Boolean> editInfo(@RequestBody UserDTO userDto, UserVO userVo) {
        return new R<>(userService.updateUserInfo(userDto, userVo.getUsername()));
    }
    /**
     * 根据角色id获取对应的用户列表
     *
     * @param roleId  角色ID
     * @return 用户列表
     */
    @GetMapping("/userList/{roleId}/{communityId}")
    public List<SysUser> userList(@PathVariable Integer roleId,@PathVariable String communityId) {
        return userService.selectListByRoleId(roleId,communityId);
    }

    @RequestMapping("/getUserId")
    public int getUserId(UserVO userVo) {
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.setSqlSelect("max(user_id)+1 as userId");
        List<SysUser> result = userService.selectList(entityWrapper);
        if(result!=null&&result.size()>0){
            return  result.get(0).getUserId();
        }else{
            return 1;
        }

    }

    /**
     * 根据当前登录返回园区树列表
     *
     * @return
     */
    @GetMapping(value = "/getCompanyTreeCurrentUser")
    public List<SelectBean> getCompanySCurrentUser() {
        Claims claims = getCurrentUserInfo();
        String currentUserName = (String) claims.get("user_name");
        ResponseUtil u = new ResponseUtil();
        return userService.getCompanyTreeCurrentUser(currentUserName);
//        return userService.getCompanySCurrentUser(currentUserName);
    }
}
